package com.hnyyac.ad.mds

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper

import android.util.Log
import android.view.ViewGroup
import androidx.lifecycle.LiveData
import com.bytedance.sdk.openadsdk.TTAdConfig
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.mediation.init.MediationConfig
import com.bytedance.sdk.openadsdk.mediation.init.MediationConfigUserInfoForSegment
import com.google.gson.Gson
import com.hnyyac.ad.mds.ben.AdIds
import com.hnyyac.ad.mds.ben.Cfs
import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.hnyyac.ad.mds.utils.BaseAdSpUtils

import com.hnyyac.ad.mds.views_notload.IAdviewNotLoadFeedListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader

object GMAds {
    var isDebug = false
    val TAG = "qin"
    var iAdViewListener: IAdViewListener? = null
    var feedListener: IAdviewNotLoadFeedListener? = null
    fun init(
        context: Activity,
        cfs: Cfs,
        initCallback: InitCallback? = null // 新增回调参数

    ) {
           KadControler.context = context
          // 解析 ad_config.json  解析各项目的 show ID 列表
            val jsonSb = StringBuilder()
            context.assets.open("ad_config.json").bufferedReader(Charsets.UTF_8).useLines {
                it.forEach {
                    jsonSb.append(it)
                }
            }
            jsonSb.toString().let {
                LLogs.info(TAG,"ad_config: $it")
                Gson().fromJson(it, AdIds::class.java)
            }.ids.apply {
                KadControler.videoShowIds = this.videos
                KadControler.cpShowIds = this.chapins
            }


        if (TTAdSdk.isInitSuccess()) {
             Log.i("qin", "isInitSuccess")
             initCallback?.onSuccess() // 通知初始化成功
            // KadControler.fristFillCache()
        }else{
            TTAdSdk.init(context, buildConfig(context, cfs));
            TTAdSdk.start(object : TTAdSdk.Callback {
                override fun success() {
                    Log.i("qin", "广告sdk加载成功")
                    //   KadControler.init(context)
                     KadControler.fristFillCache()
                     initCallback?.onSuccess()

                }

                override fun fail(code: Int, msg: String) {
                    Log.i("qin", "广告sdk加载失败")
                    initCallback?.onFailed(code, msg) // 通知初始化失败
                }
            })
        }


    }

    // 新增设置 feedListener 的方法
    fun setupLoadListener(iAdViewListener: IAdViewListener) {
        this.iAdViewListener = iAdViewListener
    }

    // 新增设置 feedListener 的方法
    fun setupFeedListener(listener: IAdviewNotLoadFeedListener) {
        this.feedListener = listener
    }


    private fun buildConfig(context: Context, cfs: Cfs): TTAdConfig? {
        return TTAdConfig.Builder().also { builder ->
            builder.appId(cfs.gromoreppId) // 应用ID
            builder.useMediation(true)
            builder.directDownloadNetworkType(2,3,4,5,6)
            builder.supportMultiProcess(true).debug(true)// 开启多进程
            // 设置 MediationConfig
            builder.setMediationConfig(
                MediationConfig.Builder() // 创建 MediationConfig 的 Builder
                   // .setCustomLocalConfig(readLoclGromorejson1(context)) // 设置本地配置
                    .setMediationConfigUserInfoForSegment(getUserInfoForSegment()) // 设置用户信息
                    .build() // 构建 MediationConfig
            )
        }.build()
    }

    private fun getUserInfoForSegment(): MediationConfigUserInfoForSegment? {
        var channelId_get = BaseAdSpUtils.getInstance().getString(BaseAdConstants.CHANNEL_ID_GET,"")
        // Log.e("qin","当前渠道ID：$channelId_get")
        var userInfoForSegment: MediationConfigUserInfoForSegment? = MediationConfigUserInfoForSegment()
        userInfoForSegment?.channel= channelId_get//传入渠道id
        return userInfoForSegment
    }

    fun loadAd(activity:  Activity,position :Int, adtype: IAdType): LiveData<IAdView?> {
        return KadControler.loadAd(activity = activity, position=position, adType = adtype)
    }

    /**
     * 读取gromore本地的广告配置文件，方便测试，解决不返回广告的问题
     */
    fun readLoclGromorejson1(context: Context): JSONObject? {
        var localConfig: JSONObject? = null
        var reader: BufferedReader? = null
        try {
            val builder = java.lang.StringBuilder()
            reader =
                BufferedReader(InputStreamReader(context.assets.open("site_config_5669830")))
            var line: String?
            while ((reader.readLine().also { line = it }) != null) {
                builder.append(line)
            }
            localConfig = JSONObject(builder.toString())
        } catch (e: Throwable) {
        } finally {
            try {
                reader?.close()
            } catch (e: Throwable) {
            }
        }

        return localConfig
    }

    interface InitCallback {
        fun onSuccess()
        fun onFailed(code: Int, msg: String)
    }
}